package com.wish.bioPool;

import com.wish.bio.ServerHandle;
import com.wish.common.MyUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 此处使用带线程池的队列实现server（client端，可以直接复用SmartClient）
 *
 * @author tantexian
 * @since 2016/6/24
 */
public class RobotPoolServer {

    public static void main(String[] args) {
        final int maxThreads = args.length >= 1 ? Integer.parseInt(args[0]) : 1000;
        final int port = args.length >= 1 ? Integer.parseInt(args[0]) : MyUtils.getDefaultPort();

        try {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("I,m a smart robot and wait for you ask. [I'm listen on prot " + port + "]\n");

            // 此处相较于RobotPoolServer，多了个线程限制。前端无论多少请求过来，如果请求数量少于maxThreads，
            // 则直接起线程执行，如果大于maxThreads，则放到队列中排队等待。这样并发很高时候，队列会很大
            // 当然也可以使用ThreadPoolExecutor的固定队列大小实现，具体参考test下的com.wish.bioPool.ThreadPoolExecutorTest.class示例
            ExecutorService executorService = Executors.newFixedThreadPool(maxThreads);

            while (true) {
                Socket socket = serverSocket.accept();
                executorService.execute(new ServerHandle(socket));
            }

        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
